<template>
  <div class="login">
      <p class="login-title">登录</p>
      <div class="login-content">
          <div class="login-main">
              <div class="login-container">
                  <el-form
                      ref="ruleFormRef"
                      label-width="120px"
                      class="demo-ruleForm"
                      :model="userinfo"
                      :rules="rules"
                  >
                      <el-form-item label="用户名" prop="username">
                          <el-input v-model="userinfo.username"/>
                      </el-form-item>

                      <el-form-item label="密码" prop="password">
                          <el-input  type="password" v-model="userinfo.password"/>
                      </el-form-item>

                      <el-form-item>
                          <el-button type="success" @click="login(ruleFormRef)">
                              登录
                          </el-button>
                      </el-form-item>

                  </el-form>
              </div>
          </div>
      </div>

  </div>
</template>

<script setup>
import {LoginMethod} from '@/api/index'
import {setToken} from '@/utils/inform'
import {reactive,ref} from 'vue'
import {useRouter} from 'vue-router'
const router=useRouter()
const ruleFormRef=ref();
const userinfo=reactive({
  username:'fred',
  password:'root'
})

// 表单校验处理
const rules=reactive({
  account:[
    {required:true,message:'请输入用户名',trigger:'blur'},
    {min:2,max:18,message:'长度在2-20个字符',trigger:'blur'}
  ],
  password:[
    {required:true,message:'请输入密码',trigger:'blur'},
    {min:6,max:18,message:'长度6-18个字符',trigger:'blur'}
  ]
})

// 登录处理方法
function login(form){
     form.validate( async valid=>{
      // 校验
      if(valid){
          let res=await LoginMethod(userinfo);
          let {uid,token}=res.data;
          if(uid){
            setToken(token);
            // 跳转到首页
            router.push('/home')
          }else{
            alert('获取用户信息失败')
          }
      }else{
        // 校验失败
        alert('校验表单失败')
      }
     })

}

</script>